//
//  PlayViewController.m
//  音乐播放器
//
//  Created by xalo on 16/1/4.
//  Copyright © 2016年 zhiying.com. All rights reserved.
//

#import "PlayViewController.h"
#import "UIImageView+WebCache.h"
@interface PlayViewController ()<UITableViewDataSource,UITableViewDelegate>
- (IBAction)previousBtn:(id)sender;
- (IBAction)playBtn:(id)sender;
- (IBAction)nextBtn:(id)sender;
- (IBAction)changeBytimeSlider:(id)sender;
- (IBAction)changeByVoiceSlider:(id)sender;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *changeByVoiceSlider;
@property (weak, nonatomic) IBOutlet UISlider *changeBytimeSlider;
@property (weak, nonatomic) IBOutlet UIImageView *imageIcon;
@property (weak, nonatomic) IBOutlet UITableView *LrcTableView;
@property (weak, nonatomic) IBOutlet UIButton *addVoiceBtn;
@property (weak, nonatomic) IBOutlet UIButton *reduceVoiceBtn;
@property(nonatomic,retain)NSMutableArray *lrcArrary;//歌词正文
@property(nonatomic,retain)NSMutableArray *timeArrary;//时间正文
@end

@implementation PlayViewController



//给各种控件赋值
- (void)setPlayInfoWithMode:(MusicModel *)model{
   
    [self.imageIcon sd_setImageWithURL:[NSURL URLWithString:model.picUrl]];
    self.navigationItem.title = model.name;
    
    //因为每次的歌词和事件都是不一样的 每当更换歌曲就要重新初始化数组
    
    self.timeArrary = [NSMutableArray array];
    self.lrcArrary = [NSMutableArray array];
    NSArray *tempArr = [self.musicModel.lyric componentsSeparatedByString:@"\n"];
    //循环取出所有的小字符串
    for (NSString *tempString in tempArr) {
        //将小字符串用]号分隔为事件扯正文
        NSLog(@"%@",tempString);
        NSArray *lrc = [tempString componentsSeparatedByString:@"]"];
       
        //有歌词并且有时间 就放在数组里
        
        if (lrc.count == 2) {
            //把歌词放入数组
            
            if (![lrc[1] isEqualToString:@""]) {
                //把歌词时间放入数组
                [self.timeArrary addObject:[lrc[0] substringWithRange:NSMakeRange(1, 5)]];
                [self.lrcArrary addObject:lrc[1]];

            }
        }
//        NSString *times = lrc[0];
//        //截取出需要的字符放进数组
//        [self.timeArrary addObject:[lrc[0]substringWithRange:NSMakeRange(1, 5)]];
//        NSLog(@"%@",[times substringWithRange:NSMakeRange(1, 5)]);
    }

    NSLog(@"%@",tempArr);
    NSLog(@"%@",self.lrcArrary);
    NSLog(@"%@",self.timeArrary);
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    NSLog(@"%@",self.musicModel.name);
//
//    self.navigationItem.title = self.musicModel.name;
//    [self.imageIcon sd_setImageWithURL:[NSURL URLWithString:self.musicModel.picUrl]];
    
    
    self.imageIcon.layer.masksToBounds = YES;
    self.imageIcon.layer.cornerRadius = self.imageIcon.frame.size.width/2-18;
    
    [self setPlayInfoWithMode:self.musicModel];
    
    //实现播放器的block获取参数
    [musicPlayerCenter defaultCenter].timeBlock = ^(CGFloat current,CGFloat total){
        NSLog(@"当前时间%f， 总时间%f",current,total);
    
        self.startTimeLabel.text =[self timeToString:current];
        self.endTimeLabel.text = [self timeToString:total];
        self.changeBytimeSlider.maximumValue = total;
        self.changeBytimeSlider.value = current;
        [self selectRowInTableViewWithTime:current];
        [UIView animateWithDuration:1 animations:^{
            self.imageIcon.transform = CGAffineTransformRotate(self.imageIcon.transform, 0.1);
        }];
    };
    
   
  
    
    
    
    self.navigationController.navigationBar.translucent = NO;
    self.LrcTableView.delegate = self;
    self.LrcTableView.dataSource = self;
    self.LrcTableView.separatorStyle= UITableViewCellSeparatorStyleNone;
   
   
}
//找出当前正在播放的歌词
- (void)selectRowInTableViewWithTime:(CGFloat)currentTime{
    //循环从时间数组中找出与当前事件相同的下标
    
    for (int i =0; i<self.timeArrary.count; i++) {
        NSString *tempString = self.timeArrary[i];
        //将时间分割为分数和秒数
        NSArray *tempArr = [tempString componentsSeparatedByString:@":"];
        NSLog(@"%@",tempArr);
        //将字符串转换为最终的时间
        NSInteger time = [tempArr[0]integerValue]*60  +[tempArr[1]integerValue];
        //比较时间
        if (time == currentTime) {
            //标记时间相等的下标
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            //选中tableView
            [self.LrcTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
            break;
            
        }
    }
 
}




- (NSString *)timeToString:(CGFloat)time{
    NSInteger M = (int)time / 60;
    NSInteger S = (int)time%60;
    return [NSString stringWithFormat:@"%ld:%ld",(long)M,(long)S];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.lrcArrary.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    static NSString *identifier = @"cell";
    
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc ]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        cell.textLabel.highlightedTextColor = [UIColor greenColor];
        cell.textLabel.numberOfLines = 0;
        cell.backgroundColor = [UIColor orangeColor];
        cell.alpha = 1.0;

    }
    cell.textLabel.text = self.lrcArrary[indexPath.row];
    
    
    return cell;
}
/*
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *string = self.lrcArrary[indexPath.row];
    CGRect frame = [string boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 10000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17] forKey:NSFontAttributeName] context:nil];
    return frame.size.height+10;
}*/


// 返回cell高度
//- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSString *string = self.lrcArrary[indexPath.row];
//    CGRect frame = [string boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 10000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17] forKey:NSFontAttributeName] context:nil];
//    return frame.size.height;
//}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)previousBtn:(id)sender {
    //发送上一曲的通知
    [[NSNotificationCenter defaultCenter]postNotificationName:@"before" object:self];
}

- (IBAction)playBtn:(id)sender {
    if ([musicPlayerCenter defaultCenter].isPlaying) {
        [[musicPlayerCenter defaultCenter]stop];
        
    }else{
        [[musicPlayerCenter defaultCenter]play];
    }
    
}

- (IBAction)nextBtn:(id)sender {
    //发送下一曲的通知
    [[NSNotificationCenter defaultCenter]postNotificationName:@"next" object:nil];
}

- (IBAction)changeBytimeSlider:(id)sender {
    UISlider *slider = sender;
    //构造一个CMTime
    CMTime time = CMTimeMake(slider.value, 1);
    //设置播放时间
    [[musicPlayerCenter defaultCenter].player seekToTime:time];
}

- (IBAction)changeByVoiceSlider:(id)sender {
    //音量是0-1
    UISlider *slider =sender;
    [musicPlayerCenter defaultCenter].player.volume =slider.value;
    
}
@end
